package cn.liberg.coder.tool.template;

import cn.liberg.coder.tool.LibergToolException;
import cn.liberg.coder.tool.core.Formats;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class CacheGroup {
    String groupCap = "0";
    List<CacheField> list = new ArrayList<>();

    String type;//目前支持CachedColumnPair和CachedColumnTrio两种
    String typeArgs;
    String columnName;
    String callArgs;

    public CacheGroup() {
    }

    public CacheGroup(CacheField field) {
        addField(field);
    }

    private static int compareCap(String x, String y) {
        if (x.length() != y.length()) {
            return x.length() - y.length();
        } else {
            return x.compareTo(y);
        }
    }

    public void addField(CacheField field) {
        list.add(field);
        if (compareCap(groupCap, field.groupCap) < 0) {
            groupCap = field.groupCap;
        }
    }

    public void build() throws LibergToolException {
        //组内根据seq值，由小到大排序
        list.sort(Comparator.comparingInt(x -> x.seq));
        if (list.size() == 2) {
            buildPair();
        } else if (list.size() == 3) {
            buildTrio();
        } else {

        }
    }

    private void buildPair() {
        CacheField f1 = list.get(0);
        CacheField f2 = list.get(1);
        type = "CachedColumnPair";
        typeArgs = f1.type + ", " + f2.type;
        columnName = "$" + f1.filedName + "$" + f2.filedName;
        callArgs = "column" + Formats.upperEntityField(f1.filedName)
                + ", "
                + "column" + Formats.upperEntityField(f2.filedName)
                + ", "
                + groupCap;
    }

    private void buildTrio() {
        CacheField f1 = list.get(0);
        CacheField f2 = list.get(1);
        CacheField f3 = list.get(2);
        type = "CachedColumnTrio";
        typeArgs = f1.type + ", " + f2.type + ", " + f3.type;
        columnName = "$" + f1.filedName + "$" + f2.filedName + "$" + f3.filedName;
        callArgs = "column" + Formats.upperEntityField(f1.filedName)
                + ", "
                + "column" + Formats.upperEntityField(f2.filedName)
                + ", "
                + "column" + Formats.upperEntityField(f3.filedName)
                + ", "
                + groupCap;
    }
}
